package com.xiao.xin.core.Util;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.xiao.xin.core.exception.UserLoginException;
import com.xiao.xin.core.domain.User;

/***
 * Token工具类
 */
public class JwtUtil {

    private static final String SingKey = "xiaoxin";


    /***
     * 生成Token
     * @param user
     * @return
     */
    public static String generateToken(User user){
       return JWT.create()
                .setExpiresAt(DateTime.now().offsetNew(DateField.MINUTE,30))
               .setPayload("userId",user.getId())
               .setPayload("username",user.getUsername())
               .setKey(SingKey.getBytes())
                .sign();
    }

    /***
     * 解析token
     * @param token
     * @return
     */
    public static User parseToken(String token){
        JWT jwt = null;
        try {
            jwt = JWTUtil.parseToken(token);
        } catch (IllegalArgumentException e) {
            throw new UserLoginException("登录失败，未授权");
        }
        boolean verify = jwt.setKey(SingKey.getBytes()).verify();
        if (!verify) throw new UserLoginException("请重新登录，Token已失效");

        return User
                .builder()
                .id(Long.valueOf(jwt.getPayload("userId").toString()))
                .username(jwt.getPayload("username").toString())
                .build();
    }





}
